package com.hds.common.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ReadExcelUtils {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Workbook wb;
    private Sheet sheet;
    private Row row;

    public ReadExcelUtils(String filepath) {
        if(filepath==null){
            return;
        }
        String ext = filepath.substring(filepath.lastIndexOf("."));
        try {
            InputStream is = new FileInputStream(filepath);
            if(".xls".equals(ext)){
                wb = new HSSFWorkbook(is);
            }else if(".xlsx".equals(ext)){
                wb = new XSSFWorkbook(is);
            }else{
                wb=null;
            }
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException", e);
        } catch (IOException e) {
            logger.error("IOException", e);
        }
    }


    /**
     * 读取Excel表格表头的内容
     * @return String 表头内容的数组
     */
    public String[] readExcelTitle() throws Exception{
        if(wb==null){
            throw new Exception("Workbook对象为空！");
        }
        Integer sheetCount = wb.getNumberOfSheets();
        sheet = wb.getSheetAt(0);
        row = sheet.getRow(0);
        // 标题总列数[   获取有记录的行数，即：最后有数据的行是第n行，前面有m行是空行没数据，则返回n-m； ]
        int colNum = row.getPhysicalNumberOfCells();

        String[] title = new String[colNum];
        for (int i = 0; i < colNum; i++) {
            // title[i] = getStringCellValue(row.getCell((short) i));
            title[i] = row.getCell(i).getStringCellValue();
        }
        return title;
    }

    /**
     * 读取Excel数据内容
     * @return Map 包含单元格数据内容的Map对象
     */
    public Map<Integer, Map<Integer,Object>> readExcelContent() throws Exception{
        if(wb==null){
            throw new Exception("Workbook对象为空！");
        }
        Map<Integer, Map<Integer,Object>> content = new HashMap<Integer, Map<Integer,Object>>();

        Integer sheetCount = wb.getNumberOfSheets();
        if(sheetCount == 0)throw new Exception("电子表格不能为空");
        System.out.println("sheetCount = "+sheetCount);



        for (int ii=0; ii<sheetCount; ii++){
            sheet = wb.getSheetAt(ii);
            // 得到总行数
            int rowNum = sheet.getLastRowNum();
            System.out.println("sheet:"+sheet.getSheetName());
            System.out.println("总行数："+rowNum);
            row = sheet.getRow(0);
            int colNum = row.getPhysicalNumberOfCells();

            // 正文内容应该从第二行开始,第一行为表头的标题
            for (int i = 1; i <= rowNum; i++) {
                row = sheet.getRow(i);
//            row.getCell(i).setCellType(XSSFCell.CELL_TYPE_STRING);
                int j = 0;
                Map<Integer,Object> cellValue = new HashMap<Integer, Object>();
                while (j < colNum) {
                    Cell cell_ = row.getCell(j);

//                Date d = cell_.getDateCellValue();
//                logger.info("d="+d);
//                cell_.setCellType(XSSFCell.CELL_TYPE_STRING);
                    Object obj = getCellFormatValue(cell_);
                    cellValue.put(j, obj);
                    j++;
                }
                content.put(i, cellValue);
                System.out.println("======"+content);
            }
        }


        return content;
    }

    /**
     * 根据Cell类型设置数据
     * @param cell
     * @return Object
     */
    private Object getCellFormatValue(Cell cell) {
        Object cellvalue = "";
        if (cell != null) {

            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:// 如果当前Cell的Type为NUMERIC
                case Cell.CELL_TYPE_FORMULA: {
                    // 判断当前的cell是否为Date
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date类型则，转化为Data格式
                        // data格式是带时分秒的：2013-7-10 0:00:00
                        // cellvalue = cell.getDateCellValue().toLocaleString();


                        // data格式是不带带时分秒的：2013-7-10
                        Date date = cell.getDateCellValue();
                        cellvalue = date;
                    } else {
                        // 如果是纯数字转为字符串类型
                        // 取得当前Cell的数值
                        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                        cellvalue = String.valueOf(cell);
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:// 默认的Cell值
                    cellvalue = "";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }

}
